package afcp.alumni.action.page;

import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.action.base.PageAction;
import afcp.alumni.model.SearchResult;
import afcp.alumni.model.db.Member;
import afcp.alumni.service.MemberService;
import afcp.alumni.util.Conf;

/**
 * Action bean for the member page "/WEB-INF/jsp/membres.jsp".
 * 
 * @author Antoine
 * @see PageAction
 * 
 */
@UrlBinding(value=MembersAction.URL+"/{q}")// TODO revoir le formulaire pour qu'il renseigne correctement le paramètre q
//@Secure(roles="ADMIN")
public class MembersAction extends PageAction implements ValidationErrorHandler {
	
	private static final Log logger = LogFactory.getLog(MembersAction.class);

	public static final String URL = "/members";
	@Override
	public String getUrl() {
		return URL;
	}
	
	// App-relative path to the default JSP file
	private static final String JSP = "/WEB-INF/jsp/members.jsp";

//	@Autowired
	@SpringBean
	private MemberService memberService;
//	private static MemberServiceImpl memberService = SF.member();

	@Override
	public String getTitle() {
		return msg("members.title");
	}

	@Override
	protected String defaultJsp() {
		return JSP;
	}

//	@Override
//	@Before
//	protected void setPageVisitedBoolean() {
//		setMembres();
//	}

	@Override
	@DefaultHandler
	public Resolution view() {
		return this.toJsp();
	}
	
	// Partie recherche de membres

	@Validate(on="search", maxlength=255)
	private String q;
	
	public String getQ() {
		return q;
	}
	public void setQ(String q) {
		this.q = q;
	}
	
	// Fin partie recherche de membres
	
	// List of members paginated
	public static final String PAGE_PARAM = "p";

	private int p = 1;
	private int pp = Integer.parseInt(Conf.get("pagination.perpage"));
	// param pp (per page)
	public void setPp(int perPage) {
		pp = perPage;
	}
	
	// param p (page)
	public void setP(int page) {
		p = page;
	}

	private SearchResult<Member> members;

	// Boolean initially added because the method was called twice (wrong
	// configuration). Its now quite useless, but still a security.
	private boolean queried = false;

	@Before(stages = LifecycleStage.CustomValidation)
	private void queryMembers() {
		if (!queried) {
			queried = true;

			if (q == null) {
				logger.info("search members with empty query. Returning "
						+ "a list with all members.");
				context.setQuery(null);
				
//				Cursor cursor = getCursor(p);
//				if (cursor != null || p ==  1) {
//					System.out.println("by cursor");
//					members = memberService.getNextMembers(p, pp, cursor);
//					setCursor(p + 1, members.getCursor());
//				} else {
//					System.out.println("by range");
					members = memberService.getMembersOfPage(p, pp);
//					setCursor(p + 1, members.getCursor());
//				}
				
			} else {
				logger.info("search members with query: " + q);
				context.setQuery(q);
				members = memberService.searchMembers(q, p, pp);
				if (members != null && logger.isInfoEnabled()) {
					int size = members.getList().size();
					logger.info("Found " + size + " result"
							+ (size > 1 ? "s" : "") + " over "
							+ members.getTotalResults() + " total results.");
					for (Member member : members.getList()) {
						logger.info(member == null ? "null member"
								: ("Last name: " + member.getLastName()
										+ " ; first name: " + member
										.getFirstName()));
					}
				}
			}
			members.initPagination(getCurrentUrl(), PAGE_PARAM);
		}
	}
	
	public SearchResult<Member> getMembersFound() {
		return members;
	}
	
	// delegate methods
	@ValidationMethod
	public void checkPageValue(ValidationErrors errors) {
		members.checkPageValue(errors);
	}

//	public int getP() {
//		return members.getPage();
//	}
//	
//	public int getpMax() {
//		return members.getpMax();
//	}
//
//	public boolean getHasNextPage() {
//		return members.getHasNextPage();
//	}
//
//	public boolean getHasPreviousPage() {
//		return members.getHasPreviousPage();
//	}
//
//	public String getNextPageUrl() {
//		return members.getNextPageUrl();
//	}
//
//	public String getPreviousPageUrl() {
//		return members.getPreviousPageUrl();
//	}
	// end delegate methods
	// end list of members paginated

	@Override
	public Resolution handleValidationErrors(ValidationErrors errors)
			throws Exception {
		return this.toJsp();
	}
	
}
